package com.xxkk.spring_boot_web.sdk.XnetPay;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.IOException;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

public class XnetPaySDK {
    private static final OkHttpClient sHttpClient = new OkHttpClient.Builder()
            .readTimeout(1, TimeUnit.MINUTES)
            .build();

    //充值请求代收
    public static void recharge() {
        try {
            TreeMap<String, String> map = new TreeMap<String, String>();
            map.put("mch_id", "12060141");// 印尼商户号
            map.put("subject", "subject");// 商品名称
            map.put("body", "body");// 商品描述
            map.put("trade_type", "QUICK.QRIS");//QUICK.GCASH // 银行虚拟账户支付 QUICK.BANKVA // QUICK.QRIS
            map.put("total_fee", "10000"); // 支付金额（印尼盾）
            map.put("out_trade_no", String.valueOf(System.currentTimeMillis()));
            map.put("notify_url", "http://google.com");
            map.put("return_url", "http://google.com");
            map.put("currency", "IDR"); // 币种：印尼盾
            map.put("attach", "{  name: 'Budi Santoso',   phone: '082122965511',    email: 'budi@example.com',   ectCode: 'IDR'  }");// 额外参数
            map.put("sign", SignUtil.buildSign(map, "3d462b5c9d3e38f1babb81148351dd55"));// 印尼商户密钥

            String body = JSONObject.toJSONString(map);
            System.out.println(body);
            String url = "https://xnetpay.net/itnpay/unifiedorder";

            String res = request(url, body);
            System.out.println(res);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String request(String url, String body) throws IOException {
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(mediaType, body);
        Request.Builder builder = new Request.Builder()
                .url(url)
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .post(requestBody);
        Request request = builder.build();
        Response response = sHttpClient.newCall(request).execute();
        return response.body().string();
    }

    public static void main(String[] args) {
        recharge();
    }
}
